
package com.plian.system.service.pm.property.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.pm.property.PropertyRecordDao;
import com.plian.system.dto.pm.property.PropertyInfoDTO;
import com.plian.system.entity.pm.property.*;
import com.plian.system.entity.sys.Org;
import com.plian.system.mapper.pm.property.PropertyChangeMapper;
import com.plian.system.model.page.Page;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.property.*;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.transfer.ITransferFlowService;
import com.plian.system.vo.pm.property.PropertyChangeVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.pm.property.PropertyChangeWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *  服务实现类
 *
 * @author jianglei
 * @since 2019-12-05
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyChangeServiceImpl extends ServiceImpl<PropertyChangeMapper, PropertyChange> implements IPropertyChangeService {

    private IPropertyService propertyService;

    private IContributorChangeService contributorChangeService;

    private IShareholdingChangeService shareholdingChangeService;

    private IPartnerOutboundChangeService partnerOutboundChangeService;

    private IPartnerSituationChangeService partnerSituationChangeService;

    private IPropertyBasicsService propertyBasicsService;

    private IContributorBasicsService contributorBasicsService;

    private IShareholdingBasicsService shareholdingBasicsService;

    private IPartnerOutboundBasicsService partnerOutboundBasicsService;

    private IPartnerSituationBasicsService partnerSituationBasicsService;

    private IPropertyRecordService propertyRecordService;

    private IContributorRecordService contributorRecordService;

    private IShareholdingRecordService shareholdingRecordService;

    private IPartnerOutboundRecordService partnerOutboundRecordService;

    private IPartnerSituationRecordService partnerSituationRecordService;

    private PropertyRecordDao propertyRecordDao;

    private ITransferFlowService transferFlowService;

    private GzwProperties gzwProperties;

    private PropertyChangeWrapper propertyChangeWrapper;

    private IOrgService orgService;

    private FileService fileService;

    @Override
    public String checkList(PropertyInfoDTO propertyInfoDTO, String competentOrganization) {
        List<PropertyChange> propertyChangeList = propertyInfoDTO.getPropertyChangeList();
        if (CollectionUtil.isEmpty(propertyChangeList)){
            return "数据为空";
        }

        Property gzwProperty = propertyService.findByOrgId(competentOrganization);
        if (gzwProperty == null){
            return  "该账号所属国资委对应产权数据未配置!";
        }
        return check(gzwProperty.getId(), propertyInfoDTO, propertyChangeList, competentOrganization, String.valueOf(FormStatusConstant.FINISH), 1);
    }

    private String check(String parentId, PropertyInfoDTO propertyInfoDTO, List<PropertyChange> propertyChangeList, String competentOrganization, String status, int checkType){
        List<PropertyBasics> existPropertyList = propertyBasicsService.list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getStatus, FormStatusConstant.FINISH).eq(PropertyBasics::getCompetentOrganization, competentOrganization));
        List<String> existInitialId = Optional.ofNullable(existPropertyList).orElse(new ArrayList<>()).stream().map(PropertyBasics::getId).collect(Collectors.toList());
        Map<String, List<PropertyChange>> map = propertyChangeList.stream().filter(p -> StringUtil.isNotBlank(p.getInitialId()))
                .collect(Collectors.groupingBy(PropertyChange::getInitialId));
        StringBuilder message = new StringBuilder();

        map.forEach((k, v) -> {
            if (!existInitialId.contains(k)){
                if (message.length() > 0){
                    message.append(",");
                }
                message.append("propertyId = " + k + "，" + v.get(0).getOrgName() + "在登记表中不存在");
                return;
            }

            for (PropertyChange change : v){
                if(StringUtil.isBlank(change.getParentId())){
                    change.setParentId(parentId);
                }
                if (change.getUpdateTime() == null){
                    change.setUpdateTime(change.getCreateTime());
                }
                change.setIsPrivateMix(0);
                if (StringUtil.isNotBlank(change.getActualCapital5())){
                    BigDecimal bigDecimal = BigDecimalUtil.toBigdecimal(change.getActualCapital5());
                    if (bigDecimal.compareTo(new BigDecimal(0)) == 1){
                        change.setIsPrivateMix(1);
                    }
                }
                change.setStatus(status);
                change.setFormType(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM));
                change.setCompetentOrganization(competentOrganization);
            }
        });
        List<String> existIds = propertyChangeList.stream().map(PropertyChange::getId).collect(Collectors.toList());
        message.append(PropertyHelper.checkContributor(propertyInfoDTO.getContributorChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkShareholding(propertyInfoDTO.getShareholdingChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkPartnerOutbound(propertyInfoDTO.getPartnerOutboundChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkPartnerSituation(propertyInfoDTO.getPartnerSituationChangeList(), existIds, checkType));
        return message.toString();
    }

    private String unitCheck(PropertyBasics parentProperty, PropertyInfoDTO propertyInfoDTO, List<PropertyChange> propertyChangeList, String competentOrganization, String status, int checkType){
        List<PropertyBasics> existPropertyList = propertyBasicsService.list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getStatus, FormStatusConstant.FINISH).likeRight(PropertyBasics::getPropertyCode, parentProperty.getPropertyCode()));
        List<String> initialIdList = existPropertyList.stream().map(PropertyBasics::getId).collect(Collectors.toList());
        List<PropertyRecord> recordList = propertyRecordService.list(Wrappers.<PropertyRecord>lambdaQuery().in(PropertyRecord::getInitialId, initialIdList));
        List<String> existOrgCodes = Optional.ofNullable(existPropertyList).orElse(new ArrayList<>()).stream().map(PropertyBasics::getOrgCode).collect(Collectors.toList());
        Map<String, List<PropertyChange>> map = propertyChangeList.stream().filter(p -> StringUtil.isNotBlank(p.getOrgCode()))
                .collect(Collectors.groupingBy(PropertyChange::getOrgCode));
        List<PropertyChange> transferDataList = list(new LambdaQueryWrapper<PropertyChange>()
                .eq(PropertyChange::getDataSource, TokenUtil.getTokenUserId()));
        Map<String, PropertyChange> transferDataMap = transferDataList.stream()
                .filter(propertyChange -> StringUtil.isNotBlank(propertyChange.getDataSourceId()))
                .collect(Collectors.toMap(PropertyChange::getDataSourceId, propertyChange -> propertyChange));
        List<PropertyChange> noApprovalList = list(new LambdaQueryWrapper<PropertyChange>()
                .ne(PropertyChange::getStatus, FormStatusConstant.FINISH)
                .in(PropertyChange::getProId, recordList.stream().map(PropertyRecord::getId).collect(Collectors.toList())));
        Map<String, PropertyChange> noApprovalMap = noApprovalList.stream()
                .collect(Collectors.toMap(PropertyChange::getOrgCode, propertyChange -> propertyChange));

        StringBuilder message = new StringBuilder();
        Date now = new Date();
        map.forEach((k, v) -> {
            if (!existOrgCodes.contains(k)){
                if (message.length() > 0){
                    message.append(",");
                }
                message.append("orgCode = " + k + "，" + v.get(0).getOrgName() + "在登记表中不存在");
                return;
            }

            if (v.size() > 1){
                message.append("orgCode = " + k + "，" + v.get(0).getOrgName() + "，条数大于1，条数=" + v.size());
                return;
            }

            PropertyChange change = v.get(0);
            if (CollectionUtil.isNotEmpty(transferDataMap) && transferDataMap.containsKey(change.getDataSourceId())){
                PropertyChange old = transferDataMap.get(change.getDataSourceId());
                if (!String.valueOf(FormStatusConstant.UNREVIEWED).equals(old.getStatus())
                    && !String.valueOf(FormStatusConstant.REJECT).equals(old.getStatus())){
                    message.append("orgCode = " + k + "，" + v.get(0).getOrgName() + ", dataSourceId=" + change.getDataSourceId() + ", 该数据审批中或已审核");
                    return;
                }
                change.setId(old.getId());
            }else if (CollectionUtil.isNotEmpty(noApprovalMap) && noApprovalMap.containsKey(k)){
                PropertyChange old = noApprovalMap.get(k);
                if (!String.valueOf(FormStatusConstant.UNREVIEWED).equals(old.getStatus())
                        && !String.valueOf(FormStatusConstant.REJECT).equals(old.getStatus())){
                    message.append("orgCode = " + k + "，" + v.get(0).getOrgName() + ", dataSourceId=" + change.getDataSourceId() + ", 该数据审批中或已审核");
                    return;
                }
                change.setId(old.getId());
            }
            if(StringUtil.isBlank(change.getParentId())){
                change.setParentId(parentProperty.getId());
            }
            if (StringUtil.isBlank(change.getId())){
                change.setCreateTime(now);
            }
            if (change.getUpdateTime() == null){
                change.setUpdateTime(change.getCreateTime());
            }
            change.setIsPrivateMix(0);
            if (StringUtil.isNotBlank(change.getActualCapital5())){
                BigDecimal bigDecimal = BigDecimalUtil.toBigdecimal(change.getActualCapital5());
                if (bigDecimal.compareTo(new BigDecimal(0)) == 1){
                    change.setIsPrivateMix(1);
                }
            }
            change.setStatus(status);
            change.setFormType(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM));
            change.setCompetentOrganization(competentOrganization);
        });

        List<String> existIds = propertyChangeList.stream().map(PropertyChange::getDataSourceId).collect(Collectors.toList());
        message.append(PropertyHelper.checkContributor(propertyInfoDTO.getContributorChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkShareholding(propertyInfoDTO.getShareholdingChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkPartnerOutbound(propertyInfoDTO.getPartnerOutboundChangeList(), existIds, checkType));
        message.append(PropertyHelper.checkPartnerSituation(propertyInfoDTO.getPartnerSituationChangeList(), existIds, checkType));
        return message.toString();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean saveList(PropertyInfoDTO propertyInfoDTO) {
        List<PropertyChange> propertyChangeList = propertyInfoDTO.getPropertyChangeList()
                .stream().filter(p -> StringUtil.isNotBlank(p.getInitialId())).collect(Collectors.toList());
        List<String> propertyIds = propertyChangeList.stream().map(PropertyChange::getId).collect(Collectors.toList());
        List<ContributorChange> contributorChangeList = propertyInfoDTO.getContributorChangeList();
        List<ShareholdingChange> shareholdingChangeList = propertyInfoDTO.getShareholdingChangeList();
        List<PartnerOutboundChange> partnerOutboundChangeList = propertyInfoDTO.getPartnerOutboundChangeList();
        List<PartnerSituationChange> partnerSituationChangeList = propertyInfoDTO.getPartnerSituationChangeList();
        String tokenUserId = TokenUtil.getTokenUserId();
        for (PropertyChange propertyChange : propertyChangeList){
            propertyChange.setDataSource(tokenUserId);
        }
        boolean result = saveOrUpdateBatch(propertyChangeList);

        contributorChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(contributorChangeList)){
            contributorChangeList.forEach(p -> p.setProChagId(p.getPropertyId()));
            contributorChangeService.saveBatch(contributorChangeList);
        }

        shareholdingChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(shareholdingChangeList)){
            shareholdingChangeService.saveBatch(shareholdingChangeList);
        }

        partnerOutboundChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerOutboundChangeList)){
            partnerOutboundChangeService.saveBatch(partnerOutboundChangeList);
        }

        partnerSituationChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerSituationChangeList)){
            partnerSituationChangeService.saveBatch(partnerSituationChangeList);
        }

        Map<String, List<PropertyChange>> changeMap = propertyChangeList.stream().collect(Collectors.groupingBy(PropertyChange::getInitialId));

        List<PropertyChange> latestChangeList = new ArrayList<>();

        changeMap.forEach((k,v) -> {
            DateFormat df = new SimpleDateFormat(DateUtil.PATTERN_DATETIME);
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.PATTERN_DATETIME);

            if (v.size() > 1) {
                //list 集合倒叙排序
                v.sort((a2, a1) -> {
                    try {
                        return df.parse(sdf.format(a2.getUpdateTime())).compareTo(df.parse(sdf.format(a1.getUpdateTime())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return 1;
                });
            }
            latestChangeList.add(v.get(0));
        });

        Map<String, String> changeIdMap = latestChangeList.stream().collect(Collectors.toMap(PropertyChange::getId, PropertyChange::getInitialId));
        List<String> initialIds = latestChangeList.stream().map(PropertyChange::getInitialId).collect(Collectors.toList());
        List<String> latestPropertyIds = latestChangeList.stream().map(PropertyChange::getId).collect(Collectors.toList());
        propertyBasicsService.updateBatchById(latestChangeList.stream().map(propertyChange -> {
            PropertyBasics propertyBasics = new PropertyBasics();
            BeanUtils.copyProperties(propertyChange, propertyBasics);
            propertyBasics.setId(propertyChange.getInitialId());
            propertyBasics.setFormType(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM));
            return propertyBasics;
        }).collect(Collectors.toList()));

        contributorBasicsService.removeByPropertyId(initialIds);
        if (CollectionUtil.isNotEmpty(contributorChangeList)){
            contributorBasicsService.updateBatchById(contributorChangeList.stream()
                    .filter(contributorChange -> latestPropertyIds.contains(contributorChange.getProChagId())).map(contributorChange -> {
                        ContributorBasics contributorBasics = new ContributorBasics();
                        BeanUtils.copyProperties(contributorChange, contributorBasics);
                        contributorBasics.setId(changeIdMap.get(contributorChange.getProChagId()));
                        return contributorBasics;
                    }).collect(Collectors.toList()));
        }


        shareholdingBasicsService.removeByPropertyId(initialIds);
        if (CollectionUtil.isNotEmpty(shareholdingChangeList)){
            shareholdingBasicsService.updateBatchById(shareholdingChangeList.stream()
                    .filter(shareholdingChange -> latestPropertyIds.contains(shareholdingChange.getPropertyId())).map(shareholdingChange -> {
                        ShareholdingBasics shareholdingBasics = new ShareholdingBasics();
                        BeanUtils.copyProperties(shareholdingChange, shareholdingBasics);
                        shareholdingBasics.setId(changeIdMap.get(shareholdingChange.getPropertyId()));
                        return shareholdingBasics;
                    }).collect(Collectors.toList()));
        }


        partnerOutboundBasicsService.removeByPropertyId(initialIds);
        if (CollectionUtil.isNotEmpty(partnerOutboundChangeList)){
            partnerOutboundBasicsService.updateBatchById(partnerOutboundChangeList.stream()
                    .filter(partnerOutboundChange -> latestPropertyIds.contains(partnerOutboundChange.getPropertyId())).map(partnerOutboundChange -> {
                        PartnerOutboundBasics partnerOutboundBasics = new PartnerOutboundBasics();
                        BeanUtils.copyProperties(partnerOutboundChange, partnerOutboundBasics);
                        partnerOutboundBasics.setId(changeIdMap.get(partnerOutboundChange.getPropertyId()));
                        return partnerOutboundBasics;
                    }).collect(Collectors.toList()));
        }


        partnerSituationBasicsService.removeByPropertyId(initialIds);
        if (CollectionUtil.isNotEmpty(partnerSituationChangeList)){
            partnerSituationBasicsService.updateBatchById(partnerSituationChangeList.stream()
                    .filter(partnerSituationChange -> latestPropertyIds.contains(partnerSituationChange.getPropertyId())).map(partnerSituationChange -> {
                        PartnerSituationBasics partnerSituationBasics = new PartnerSituationBasics();
                        BeanUtils.copyProperties(partnerSituationChange, partnerSituationBasics);
                        partnerSituationBasics.setId(changeIdMap.get(partnerSituationChange.getPropertyId()));
                        return partnerSituationBasics;
                    }).collect(Collectors.toList()));
        }


        propertyRecordService.saveBatch(propertyChangeList.stream().map(property -> {
            PropertyRecord propertyRecord = new PropertyRecord();
            BeanUtils.copyProperties(property, propertyRecord);
            propertyRecord.setFormType(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM));
            return propertyRecord;
        }).collect(Collectors.toList()));

        contributorRecordService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(contributorChangeList)){
            contributorRecordService.saveBatch(contributorChangeList.stream().map(contributor -> {
                ContributorRecord contributorRecord = new ContributorRecord();
                BeanUtils.copyProperties(contributor, contributorRecord);
                return contributorRecord;
            }).collect(Collectors.toList()));
        }

        shareholdingRecordService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(shareholdingChangeList)){
            shareholdingRecordService.saveBatch(shareholdingChangeList.stream().map(shareholding -> {
                ShareholdingRecord shareholdingRecord = new ShareholdingRecord();
                BeanUtils.copyProperties(shareholding, shareholdingRecord);
                return shareholdingRecord;
            }).collect(Collectors.toList()));
        }

        partnerOutboundRecordService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerOutboundChangeList)){
            partnerOutboundRecordService.saveBatch(partnerOutboundChangeList.stream().map(partnerOutbound -> {
                PartnerOutboundRecord partnerOutboundRecord = new PartnerOutboundRecord();
                BeanUtils.copyProperties(partnerOutbound, partnerOutboundRecord);
                return partnerOutboundRecord;
            }).collect(Collectors.toList()));
        }

        partnerSituationRecordService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerSituationChangeList)){
            partnerSituationRecordService.saveBatch(partnerSituationChangeList.stream().map(partnerSituation -> {
                PartnerSituationRecord partnerSituationRecord = new PartnerSituationRecord();
                BeanUtils.copyProperties(partnerSituation, partnerSituationRecord);
                return partnerSituationRecord;
            }).collect(Collectors.toList()));
        }

        return result;
    }

    @Override
    public String unitCheckList(PropertyInfoDTO propertyInfoDTO, String competentOrganization) {
        List<PropertyChange> propertyList = propertyInfoDTO.getPropertyChangeList();
        if (CollectionUtil.isEmpty(propertyList)){
            return "数据为空!";
        }

        String tokenOrgId = TokenUtil.getTokenOrgId();
        PropertyBasics parentProperty = propertyBasicsService.findByOrgId(tokenOrgId);
        if (parentProperty == null){
            return  "该账号所属单位对应产权数据未配置!";
        }
        return unitCheck(parentProperty, propertyInfoDTO, propertyList, competentOrganization, String.valueOf(FormStatusConstant.UNREVIEWED), 2);

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean unitSaveList(PropertyInfoDTO propertyInfoDTO) {
        List<PropertyChange> propertyChangeList = propertyInfoDTO.getPropertyChangeList();
        List<ContributorChange> contributorChangeList = propertyInfoDTO.getContributorChangeList();
        List<ShareholdingChange> shareholdingChangeList = propertyInfoDTO.getShareholdingChangeList();
        List<PartnerOutboundChange> partnerOutboundChangeList = propertyInfoDTO.getPartnerOutboundChangeList();
        List<PartnerSituationChange> partnerSituationChangeList = propertyInfoDTO.getPartnerSituationChangeList();

        List<PropertyBasics> existPropertyList = propertyBasicsService.list(new LambdaQueryWrapper<PropertyBasics>()
                .eq(PropertyBasics::getStatus, FormStatusConstant.FINISH).eq(PropertyBasics::getCompetentOrganization, TokenUtil.getCompetentOrganization()));
        Map<String, PropertyBasics> propertyBasicsMap = existPropertyList.stream()
                .filter(propertyBasics -> StringUtil.isNotBlank(propertyBasics.getOrgCode()))
                .collect(Collectors.toMap(PropertyBasics::getOrgCode, propertyBasics -> propertyBasics));
        String tokenUserId = TokenUtil.getTokenUserId();
        String tokenOrgId = TokenUtil.getTokenOrgId();
        Map<String, String> recordMap = new HashMap<>();
        try {
            Page page = new Page(false, new PageData());
            List<PageData> recordList = propertyRecordDao.listPage(page);
            recordMap = recordList.stream()
                    .collect(Collectors.toMap(record -> record.getString("initialId"), record -> record.getString("id")));
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }


        for (PropertyChange propertyChange : propertyChangeList){
            propertyChange.setDataSource(tokenUserId);
            propertyChange.setFillOrgId(tokenOrgId);
            propertyChange.setInitialId(propertyBasicsMap.get(propertyChange.getOrgCode()).getId());
            if (propertyBasicsMap.containsKey(propertyChange.getCapitalOrgCode())){
                propertyChange.setParentId(propertyBasicsMap.get(propertyChange.getCapitalOrgCode()).getId());
            }
            if (recordMap.containsKey(propertyChange.getInitialId())){
                propertyChange.setProId(recordMap.get(propertyChange.getInitialId()));
            }
        }
        boolean result = saveOrUpdateBatch(propertyChangeList);
        List<String> propertyIds = propertyChangeList.stream().map(PropertyChange::getId).collect(Collectors.toList());
        Map<String, PropertyChange> dataSourceIdPropertyMap = propertyChangeList.stream()
                .collect(Collectors.toMap(PropertyChange::getDataSourceId, propertyChange -> propertyChange));

        contributorChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(contributorChangeList)){
            List<ContributorChange> saveList = new ArrayList<>();
            for (ContributorChange contributor : contributorChangeList){
                if (dataSourceIdPropertyMap.containsKey(contributor.getPropertyDataSourceId())){
                    contributor.setPropertyId(dataSourceIdPropertyMap.get(contributor.getPropertyDataSourceId()).getId());
                    contributor.setProChagId(contributor.getPropertyId());
                    saveList.add(contributor);
                }
            }
            contributorChangeService.saveBatch(saveList);
        }

        shareholdingChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(shareholdingChangeList)){
            List<ShareholdingChange> saveList = new ArrayList<>();
            for (ShareholdingChange shareholding : shareholdingChangeList){
                if (dataSourceIdPropertyMap.containsKey(shareholding.getPropertyDataSourceId())){
                    shareholding.setPropertyId(dataSourceIdPropertyMap.get(shareholding.getPropertyDataSourceId()).getId());
                    saveList.add(shareholding);
                }
            }
            shareholdingChangeService.saveBatch(saveList);
        }

        partnerOutboundChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerOutboundChangeList)){
            List<PartnerOutboundChange> saveList = new ArrayList<>();
            for (PartnerOutboundChange partnerOutbound : partnerOutboundChangeList){
                if (dataSourceIdPropertyMap.containsKey(partnerOutbound.getPropertyDataSourceId())){
                    partnerOutbound.setPropertyId(dataSourceIdPropertyMap.get(partnerOutbound.getPropertyDataSourceId()).getId());
                    saveList.add(partnerOutbound);
                }
            }
            partnerOutboundChangeService.saveBatch(saveList);
        }

        partnerSituationChangeService.removeByPropertyId(propertyIds);
        if (CollectionUtil.isNotEmpty(partnerSituationChangeList)){
            List<PartnerSituationChange> saveList = new ArrayList<>();
            for (PartnerSituationChange partnerSituation : partnerSituationChangeList){
                if (dataSourceIdPropertyMap.containsKey(partnerSituation.getPropertyDataSourceId())){
                    partnerSituation.setPropertyId(dataSourceIdPropertyMap.get(partnerSituation.getPropertyDataSourceId()).getId());
                    saveList.add(partnerSituation);
                }
            }
            partnerSituationChangeService.saveBatch(saveList);
        }
        if (CollectionUtil.isNotEmpty(propertyIds)){
            transferFlowService.submit(propertyIds, FormTypeConstant.PM_PROPERTYCHANGE_FORM);
        }
        return result;
    }

    @Override
    public String ythSubmitBatch(String data) {
        YthResult ythResult = new YthResult();
        //成功的id集合
        List<String> successIds = new ArrayList<>();
        //失败的id集合
        List<String> failIds = new ArrayList<>();
        //失败的原因
        List<String> failReasons = new ArrayList<>();
        //将json字符串转换成list
        List<PropertyChangeVO> dataList = JSON.parseArray(data, PropertyChangeVO.class);
        if (CollectionUtil.isEmpty(dataList)){
            failReasons.add("数据为空");
            ythResult.setFailReason(StringUtils.join(failReasons, StringPool.COMMA));
            return JSON.toJSONString(ythResult);
        }
        //已登记的数据
        List<PropertyBasics> propertyBasicsList = propertyBasicsService.list(Wrappers.<PropertyBasics>lambdaQuery()
                .eq(PropertyBasics::getStatus, FormStatusConstant.FINISH)
                .isNotNull(PropertyBasics::getOrgCode)
                .eq(PropertyBasics::getCompetentOrganization, gzwProperties.getId()));
        Map<String, PropertyBasics> propertyBasicsMap = propertyBasicsList.stream()
                .collect(Collectors.toMap(PropertyBasics::getOrgCode, Function.identity()));
        //变更中的数据
        List<PropertyChange> propertyChangeList = list(Wrappers.<PropertyChange>query().lambda()
                .eq(PropertyChange::getStatus, FormStatusConstant.FLOW).eq(PropertyChange::getCompetentOrganization, gzwProperties.getId()));

        Set<String> orgCodeList = propertyChangeList.stream().map(PropertyChange::getOrgCode).collect(Collectors.toSet());
        //查询获取可修改的老数据
        List<PropertyChange> oldList = list(new LambdaQueryWrapper<PropertyChange>()
                .isNotNull(PropertyChange::getOrgCode)
                .eq(PropertyChange::getCompetentOrganization, gzwProperties.getId())
                .in(PropertyChange::getStatus, Stream.of(FormStatusConstant.STASH,
                        FormStatusConstant.UNREVIEWED, FormStatusConstant.REJECT).collect(Collectors.toList())));
        Map<String, PropertyChange> oldOrgCodeMap = oldList.stream().collect(Collectors.toMap(PropertyChange::getOrgCode, Function.identity()));
        List<Org> orgList = orgService.getYthOrgList();
        Map<String, Org> dataSourceIdOrgMap = orgList.stream().collect(Collectors.toMap(Org::getDataSourceId, Function.identity()));
        //出资人情况
        List<ContributorChange> contributorList = new ArrayList<>();
        //合伙人登记情况
        List<PartnerSituationChange> partnerSituationList = new ArrayList<>();
        //对外投资情况
        List<PartnerOutboundChange> partnerOutboundList = new ArrayList<>();
        //境外控股人
        List<ShareholdingChange> shareholdingList = new ArrayList<>();
        List<String> removeChildIds = new ArrayList<>();
        Date now = DateUtil.now();
        for (PropertyChangeVO propertyChangeVO : dataList){
            if (!propertyBasicsMap.containsKey(propertyChangeVO.getOrgCode())){
                failIds.add(propertyChangeVO.getDataSourceId());
                failReasons.add(propertyChangeVO.getDataSourceId() + "未登记产权");
                continue;
            }
            if (!propertyBasicsMap.containsKey(propertyChangeVO.getCapitalOrgCode())){
                failIds.add(propertyChangeVO.getDataSourceId());
                failReasons.add(propertyChangeVO.getDataSourceId() + "父节点不存在");
                continue;
            }
            if (orgCodeList.contains(propertyChangeVO.getOrgCode())){
                failIds.add(propertyChangeVO.getDataSourceId());
                failReasons.add(propertyChangeVO.getDataSourceId() + "该企业变更中，不能再变更或修改");
                continue;
            }
            if (successIds.contains(propertyChangeVO.getDataSourceId())){
                failIds.add(propertyChangeVO.getDataSourceId());
                failReasons.add(propertyChangeVO.getDataSourceId() + "id重复");
                continue;
            }
            if (StringUtil.isBlank(propertyChangeVO.getNature())){
                failIds.add(propertyChangeVO.getDataSourceId());
                failReasons.add(propertyChangeVO.getDataSourceId() + "nature 性质不能为空");
                continue;
            }

            successIds.add(propertyChangeVO.getDataSourceId());
            PropertyChange entity = propertyChangeWrapper.voToEntity(propertyChangeVO);
            if (oldOrgCodeMap.containsKey(propertyChangeVO.getOrgCode())){
                entity.setId(oldOrgCodeMap.get(propertyChangeVO.getOrgCode()).getId());
                removeChildIds.add(entity.getId());
            }
            if (dataSourceIdOrgMap.containsKey(entity.getOrgId())){
                entity.setOrgId(dataSourceIdOrgMap.get(entity.getOrgId()).getId());
            }
            if (dataSourceIdOrgMap.containsKey(entity.getFillOrgId())){
                entity.setFillOrgId(dataSourceIdOrgMap.get(entity.getFillOrgId()).getId());
            }
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            entity.setInitialId(propertyBasicsMap.get(propertyChangeVO.getOrgCode()).getId());
            PropertyRecord propertyRecord = propertyRecordService.getOne(Wrappers.<PropertyRecord>lambdaQuery()
                    .eq(PropertyRecord::getInitialId, entity.getInitialId())
                    .orderByDesc(PropertyRecord::getCreateTime)
                    .last("limit 1"));
            entity.setProId(propertyRecord.getId());
            entity.setFormType(String.valueOf(FormTypeConstant.PM_PROPERTYCHANGE_FORM));
            entity.setDataSource(YthConstant.DATA_NINGBO);
            entity.setCompetentOrganization(gzwProperties.getId());
            entity.setStatus(String.valueOf(FormStatusConstant.UNREVIEWED));
            entity.setParentId(propertyBasicsMap.get(propertyChangeVO.getCapitalOrgCode()).getId());
            saveOrUpdate(entity);
            saveFile(entity, propertyChangeVO);
            switch (entity.getNature()){
                case "0":
                    //境内企业
                    if (CollectionUtil.isNotEmpty(propertyChangeVO.getContributorChangeList())){
                        for (ContributorChange contributor : propertyChangeVO.getContributorChangeList()){
                            contributor.setProChagId(entity.getId());
                        }
                        contributorList.addAll(propertyChangeVO.getContributorChangeList());
                    }
                    break;
                case "1":
                    //境外企业
                    if (CollectionUtil.isNotEmpty(propertyChangeVO.getContributorChangeList())){
                        for (ContributorChange contributor : propertyChangeVO.getContributorChangeList()){
                            contributor.setProChagId(entity.getId());
                        }
                        contributorList.addAll(propertyChangeVO.getContributorChangeList());
                    }
                    if (CollectionUtil.isNotEmpty(propertyChangeVO.getShareholdingChangeList())){
                        for (ShareholdingChange shareholding : propertyChangeVO.getShareholdingChangeList()){
                            shareholding.setPropertyId(entity.getId());
                        }
                        shareholdingList.addAll(propertyChangeVO.getShareholdingChangeList());
                    }
                    break;
                case "2":
                    //合伙企业
                    if (CollectionUtil.isNotEmpty(propertyChangeVO.getPartnerSituationChangeList())){
                        for (PartnerSituationChange partnerSituation : propertyChangeVO.getPartnerSituationChangeList()){
                            partnerSituation.setPropertyId(entity.getId());
                        }
                        partnerSituationList.addAll(propertyChangeVO.getPartnerSituationChangeList());
                    }
                    if (CollectionUtil.isNotEmpty(propertyChangeVO.getPartnerOutboundChangeList())){
                        for (PartnerOutboundChange partnerOutbound : propertyChangeVO.getPartnerOutboundChangeList()){
                            partnerOutbound.setPropertyId(entity.getId());
                        }
                        partnerOutboundList.addAll(propertyChangeVO.getPartnerOutboundChangeList());
                    }
                    break;
                default:
            }
        }
        if (CollectionUtil.isNotEmpty(removeChildIds)){
            contributorChangeService.remove(Wrappers.<ContributorChange>lambdaQuery()
                    .in(ContributorChange::getProChagId, removeChildIds));
            shareholdingChangeService.remove(Wrappers.<ShareholdingChange>lambdaQuery()
                    .in(ShareholdingChange::getPropertyId, removeChildIds));
            partnerSituationChangeService.remove(Wrappers.<PartnerSituationChange>lambdaQuery()
                    .in(PartnerSituationChange::getPropertyId, removeChildIds));
            partnerOutboundChangeService.remove(Wrappers.<PartnerOutboundChange>lambdaQuery()
                    .in(PartnerOutboundChange::getPropertyId, removeChildIds));
        }

        if (CollectionUtil.isNotEmpty(contributorList)){
            contributorChangeService.saveBatch(contributorList);
        }
        if (CollectionUtil.isNotEmpty(shareholdingList)){
            shareholdingChangeService.saveBatch(shareholdingList);
        }
        if (CollectionUtil.isNotEmpty(partnerSituationList)){
            partnerSituationChangeService.saveBatch(partnerSituationList);
        }
        if (CollectionUtil.isNotEmpty(partnerOutboundList)){
            partnerOutboundChangeService.saveBatch(partnerOutboundList);
        }


        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(StringUtils.join(failReasons, StringPool.COMMA));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    private void saveFile(PropertyChange entity, PropertyChangeVO vo){
        fileService.upYthFile(vo.getF1(), entity.getId(), "f1");
        fileService.upYthFile(vo.getF2(), entity.getId(), "f2");
        fileService.upYthFile(vo.getF3(), entity.getId(), "f3");
        fileService.upYthFile(vo.getF4(), entity.getId(), "f4");
        fileService.upYthFile(vo.getF5(), entity.getId(), "f5");
        fileService.upYthFile(vo.getF6(), entity.getId(), "f6");
        fileService.upYthFile(vo.getF7(), entity.getId(), "f7");
        fileService.upYthFile(vo.getF8(), entity.getId(), "f8");
        fileService.upYthFile(vo.getF9(), entity.getId(), "f9");
    }

}
